//
//  HomeViewController.m
//  AipuTel
//
//  Created by cretve on 15/1/15.
//  Copyright (c) 2015年 aipu. All rights reserved.
//

#import "HomeViewController.h"
#import "AppDelegate.h"
#import "ABWrappers.h"
#import "CallingViewController.h"

@interface HomeViewController ()

@property (strong, nonatomic) NSMutableArray *historyArray;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *dailView;
@property (weak, nonatomic) IBOutlet UITextField *numberField;

@end

@implementation HomeViewController

- (void)awakeFromNib
{
    self.tabBarItem.title = @"通话记录";
    self.tabBarItem.image = [[UIImage imageNamed:@"home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"home"] imageWithWhiteMask];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.title = @"点话通";
    
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"CallHistory" : @[]}];
    
    _numberField.text = @"";
    _numberField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入电话号码" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:18]}];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.historyArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:@"CallHistory"]];
    [self.tableView reloadData];
}

#pragma mark -

- (IBAction)clickedNum:(UIButton *)sender
{
    NSString* string = nil;
    if(sender.tag == 10)
        string = @"0";
    else if(sender.tag > 0)
        string = [@(sender.tag) stringValue];
    
    if(string)
        _numberField.text = [_numberField.text stringByAppendingString:string];
}

- (IBAction)clickedDail:(UIButton *)sender
{
    if(_numberField.text.length == 0)
    {
        return;
    }
    
    if([_numberField.text hasPrefix:@"1"] || [_numberField.text hasPrefix:@"0"])
    {
        if(_numberField.text.length != 11)
        {
            [UIAlertView bk_showAlertViewWithTitle:@"该电话号码不正确" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
            return;
        }
    }
    else if(_numberField.text.length < 7 || _numberField.text.length > 8)
    {
        [UIAlertView bk_showAlertViewWithTitle:@"该电话号码不正确" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        return;
    }
    
    [self callNumber:_numberField.text];
    _numberField.text = nil;
}

- (IBAction)clickedDelete:(UIButton *)sender
{
    if(_numberField.text.length > 0)
        _numberField.text = [_numberField.text substringToIndex:_numberField.text.length - 1];
}

- (IBAction)clickedHide:(UIButton *)sender
{
    _dailView.hidden = YES;
    
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (IBAction)clickedShow:(UIButton *)sender
{
    _dailView.hidden = NO;
    
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 280, 0);
}

- (void)callNumber:(NSString*)number
{
    NSDictionary* userInfo = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"UsreInfo"];
    if(userInfo.count == 0)
    {
        [UIAlertView bk_showAlertViewWithTitle:@"请先登录" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        return;
    }
    
    [_historyArray insertObject:@{@"phone": number, @"date": [NSDate date]} atIndex:0];
    
    [[NSUserDefaults standardUserDefaults] setObject:_historyArray forKey:@"CallHistory"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    CallingViewController* cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"CallingViewController"];
    cvc.number = number;
    
    [self presentViewController:cvc animated:YES completion:nil];
}

#pragma mark -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _historyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSDictionary* history = _historyArray[indexPath.row];
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* name = [appDelegate contactNameWithNumder:history[@"phone"]];
    if(name.length > 0)
    {
        cell.textLabel.text = name;
        cell.detailTextLabel.text = history[@"phone"];
    }
    else
    {
        cell.textLabel.text = history[@"phone"];
        cell.detailTextLabel.text = nil;
    }
    
    UILabel* timeLabel = (UILabel*)[cell.contentView viewWithTag:10086];
    NSDate* date = history[@"date"];
    timeLabel.text = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* history = _historyArray[indexPath.row];
    [self callNumber:history[@"phone"]];
}

@end
